package com.zhaoqi.hr.repository;

import com.zhaoqi.hr.entity.EmployerProfile;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 用工方档案数据访问层
 */
@Repository
public interface EmployerProfileRepository extends JpaRepository<EmployerProfile, Long>, JpaSpecificationExecutor<EmployerProfile> {

    /**
     * 根据用户ID查找用工方档案
     */
    Optional<EmployerProfile> findByUserId(Long userId);

    /**
     * 根据资质状态查找用工方
     */
    List<EmployerProfile> findByQualificationStatus(EmployerProfile.QualificationStatus status);

    /**
     * 根据ID查找用工方档案并主动加载User关联
     */
    @Query("SELECT ep FROM EmployerProfile ep LEFT JOIN FETCH ep.user WHERE ep.id = :id")
    Optional<EmployerProfile> findByIdWithUser(@Param("id") Long id);

    /**
     * 根据资质状态查找用工方档案并主动加载User关联（分页）
     */
    @Query(value = "SELECT ep FROM EmployerProfile ep LEFT JOIN FETCH ep.user WHERE (:status IS NULL OR ep.qualificationStatus = :status)",
           countQuery = "SELECT COUNT(ep) FROM EmployerProfile ep WHERE (:status IS NULL OR ep.qualificationStatus = :status)")
    Page<EmployerProfile> findAllWithUser(@Param("status") EmployerProfile.QualificationStatus status, Pageable pageable);

    /**
     * 根据公司名称查找用工方
     */
    Optional<EmployerProfile> findByCompanyName(String companyName);

    /**
     * 检查营业执照是否存在
     */
    boolean existsByBusinessLicense(String businessLicense);

    /**
     * 统计各资质状态的用工方数量
     */
    @Query("SELECT e.qualificationStatus, COUNT(e) FROM EmployerProfile e GROUP BY e.qualificationStatus")
    List<Object[]> countByQualificationStatus();

    /**
     * 查找保证金余额不足的用工方
     */
    @Query("SELECT e FROM EmployerProfile e WHERE e.depositBalance < :minBalance")
    List<EmployerProfile> findByDepositBalanceLessThan(@Param("minBalance") java.math.BigDecimal minBalance);
}
